const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');

const app = express();
const port = 3000;

// 配置文件上傳
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const platform = req.body.platform;
        const uploadDir = path.join(__dirname, '../public/downloads', platform);
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});

const upload = multer({ storage: storage });

// 配置靜態文件和解析器
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 版本信息存儲文件
const VERSION_FILE = path.join(__dirname, 'versions.json');

// 確保版本文件存在
if (!fs.existsSync(VERSION_FILE)) {
    fs.writeFileSync(VERSION_FILE, JSON.stringify({ versions: [] }));
}

// 原有的用戶路由
app.get('/users', (req, res) => {
    const hostid = req.query.hostid;
    const uuid = uuidv4();
    
    res.json({
        resources: [{
            uuid: uuid,
            objectId: 'obj_' + Date.now(),
            hostid: hostid
        }]
    });
});

// 版本管理頁面路由
app.get('/users/version-server', (req, res) => {
    res.sendFile('/var/www/ctdy123.com/public/index.html');
});

app.use('/users/version-server/static', express.static('/var/www/ctdy123.com/public'));

// 保留原有的版本管理相關路由
app.get('/users/version-history', (req, res) => {
    const versions = JSON.parse(fs.readFileSync(VERSION_FILE));
    res.json(versions);
});

app.post('/users/add-version', upload.single('installer'), (req, res) => {
    try {
        const { version, platform, releaseNotes } = req.body;
        const file = req.file;

        // 計算 MD5
        const fileBuffer = fs.readFileSync(file.path);
        const hashSum = crypto.createHash('md5');
        hashSum.update(fileBuffer);
        const md5 = hashSum.digest('hex');

        // 構建下載 URL
        const downloadUrl = `/downloads/${platform}/${file.filename}`;

        // 讀取現有版本
        const versions = JSON.parse(fs.readFileSync(VERSION_FILE));

        // 添加新版本
        versions.versions.push({
            version,
            platform,
            downloadUrl,
            releaseNotes,
            releaseDate: new Date().toISOString(),
            md5,
            fileName: file.filename
        });

        // 保存版本信息
        fs.writeFileSync(VERSION_FILE, JSON.stringify(versions, null, 2));

        res.json({ message: 'Version added successfully' });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

app.delete('/users/delete-version', (req, res) => {
    try {
        const { version, platform } = req.body;
        const versions = JSON.parse(fs.readFileSync(VERSION_FILE));
        
        // 找到要刪除的版本
        const versionToDelete = versions.versions.find(
            v => v.version === version && v.platform === platform
        );

        if (versionToDelete) {
            // 刪除文件
            const filePath = path.join(__dirname, '../public', versionToDelete.downloadUrl);
            if (fs.existsSync(filePath)) {
                fs.unlinkSync(filePath);
            }

            // 更新版本列表
            versions.versions = versions.versions.filter(
                v => !(v.version === version && v.platform === platform)
            );
            fs.writeFileSync(VERSION_FILE, JSON.stringify(versions, null, 2));
        }

        res.json({ message: 'Version deleted successfully' });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 檢查更新的 API
app.post('/users/check-update', (req, res) => {
    const { currentVersion, platform } = req.body;
    const versions = JSON.parse(fs.readFileSync(VERSION_FILE));
    
    const latestVersion = versions.versions
        .filter(v => v.platform === platform)
        .sort((a, b) => b.version.localeCompare(a.version))[0];
    
    if (latestVersion && latestVersion.version > currentVersion) {
        res.json(latestVersion);
    } else {
        res.json({ message: 'No update available' });
    }
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});
